import {
  types,
  openFile,
  getInputValue,
  getFormData,
} from "@/utils/index";
import conf from "@/common/config/index";
import Storage from "@/common/js/storage";
import {
  mapState
} from "vuex";
import {
  _onInput,
  resetInputValue
} from "./base";
export default {
  computed: {
    ...mapState(["pageEdit"]),
  },
  data() {
    /* eslint-disable */
    let self = this;
    let typeArr = ["error", "info", "success", "warning"];
    const message = function (opt) {
      if (self.$refs.message) {
        let type = opt.type || "success";
        let index = typeArr.indexOf(type);
        let key = typeArr[index > -1 ? index : 0];
        return self.$refs.message[key](opt);
      } else {
        return new Promise((r, reject) => reject('no ref message'));
      }
    };
    typeArr.forEach((i) => {
      message[i] = message.prototype[i] = function (text) {
        message({
          title: "",
          type: i,
          message: text,
        });
      };
    });

    return {
      // 设置属性
      imgSuffixs: ["jpg", "jpeg", "png", "gif"],
      mixinViewOptions: {
        createdIsNeed: false, // 此页面是否在创建时，调用查询数据列表接口？
        activatedIsNeed: false, // 此页面是否在激活（进入）时，调用查询数据列表接口？
        getURL: "", // 数据列表接口，API地址
        isPage: false, // 数据列表接口，是否需要分页？
        deleteURL: "", // 删除接口，API地址
        deleteIsBatchKey: "id", // 删除接口，批量状态下由那个key进行标记操作？比如：pid，uid...
        exportURL: "", // 导出接口，API地址
        isShowLoading: false, //是否显示
        reachBottom: false, //下拉加载
        pullDown: false, // 是否开启上拉刷新
        share: false, //是否分享
        ERR_OK: 200, //成功码
        ERR_KEY: "code", //判断是否成功字段
        type: "get", // 请求方式
      },
      // 默认属性
      dataForm: {}, // 查询条件
      dataInfo: {}, // 信息
      dataHeaders: {}, // 请求头
      message,
      mixinShareOptions: {
        //微信分享配置
        title: "润滑卫士",
        imageUrl: "",
        path: "",
      },
      primaryKey: "id",
    };
    /* eslint-enable */
  },
  onLoad() {
    // #ifdef MP
    if (this.mixinViewOptions.share) {
      uni.showShareMenu({
        withShareTicket: true,
        menus: ["shareAppMessage", "shareTimeline"],
      });
    }
    // #endif
    if (this.mixinViewOptions.createdIsNeed) {
      this.getDataInfo();
    }
  },
  onShow() {
    if (this.mixinViewOptions.activatedIsNeed) {
      this.getDataInfo();
    }
    if (this.pageEdit) {
      if (this.mixinViewOptions.pullDown) {
        uni.startPullDownRefresh();
      } else {
        this.getDataInfo();
      }
      this.$store.commit("setPageEdit", false);
    }
  },
  methods: {
    resetInputValue,
    _onInput,
    // 获取数据列表
    getDataInfo() {
      if (!this.mixinViewOptions.getURL) {
        return Promise.reject("请传入请求链接!");
      }
      this.dataListLoading = true;
      let isShowLoad = this.mixinViewOptions.isShowLoading;
      if (isShowLoad) {
        uni.showLoading({
          title: "加载中",
        });
      }
      let getURL = this.mixinViewOptions.getURL;
      if (this.dataForm.id && (this.mixinViewOptions.type == "get" || !this.mixinViewOptions.type)) {
        // getURL += "/" + this.dataForm.id;
      }
      let _config = {
        header: this.dataHeaders || {},
        params: {
          ...this.dataForm,
        },
      };
      if (this.mixinViewOptions.type !== "get") {
        _config = {
          ...this.dataForm,
        };
      }
      return this.$http[this.mixinViewOptions.type || 'get'](
          getURL,
          _config,
          this.dataHeaders
        )
        .then((res) => {
          this.dataListLoading = false;
          uni.hideLoading();
          if (
            res[this.mixinViewOptions.ERR_KEY] !== this.mixinViewOptions.ERR_OK
          ) {
            let data = {};
            let tmp = this.fetchComplete(false, data, res);
            this.dataInfo = tmp || data;
            return this.message.error(res.message);
          }
          let data = res.data;
          let tmp = this.fetchComplete(false, data, res);
          this.dataInfo = tmp || data;
        })
        .catch((err) => {
          uni.hideLoading();
          this.fetchComplete(true, err);
          this.dataListLoading = false;
        });
    },
    fetchComplete(err, data = {}) {
      return data;
    },
    // 删除
    deleteHandle(id) {
      this.showModal({
          title: "提示",
          content: "确认删除吗?",
          confirmColor: "#3F7DFF",
          type: "warning",
        })
        .then(() => {
          this.$http
            .delete(
              `${this.mixinViewOptions.deleteURL}${this.mixinViewOptions.deleteIsBatch ? "" : "/" + id
              }`,
              this.mixinViewOptions.deleteIsBatch ? {
                data: [id],
              } : {}
            )
            .then((res) => {
              if (res.code !== 0) {
                return this.message.error(res.message);
              }
              this.message({
                message: "成功",
                type: "success",
                duration: 500,
                onClose: () => {
                  this.$Router.go(-1);
                },
              });
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    showToast(opt = {}, icon = "none") {
      let def = {
        title: "",
        content: "",
        icon: "none",
        duration: 1500,
      };
      if (typeof opt === "string") {
        opt = {
          title: opt,
          icon,
        };
      }
      let option = Object.assign({}, def, opt);
      return new Promise(function (resolve, reject) {
        uni.showToast({
          ...option,
          success(res) {
            resolve(res);
            if (types.isFunction(option.success)) {
              option.success(res);
            }
          },
          fail(err) {
            reject(err);
            if (types.isFunction(option.fail)) {
              option.fail(err);
            }
          },
          complete() {
            if (types.isFunction(option.complete)) {
              option.complete(...arguments);
            }
          },
        });
      });
    },
    showModal(opt = {}) {
      let def = {
        title: "",
        content: "",
        confirmText: "确认",
        cancelText: "取消",
        confirmColor: "#3F7DFF",
      };
      let option = Object.assign({}, def, opt);
      return new Promise(function (resolve, reject) {
        uni.showModal({
          ...option,
          success(res) {
            resolve(res);
            if (types.isFunction(option.success)) {
              option.success(res);
            }
          },
          fail(err) {
            reject(err);
            if (types.isFunction(option.fail)) {
              option.fail(err);
            }
          },
          complete() {
            if (types.isFunction(option.complete)) {
              option.complete(...arguments);
            }
          },
        });
      });
    },
    onOpenFile: openFile,
  },
  onReachBottom() {
    if (this.mixinViewOptions.reachBottom) {
      // this.getDataInfo();
    }
  },
  async onPullDownRefresh() {
    if (this.dataForm[this.primaryKey] && this.mixinViewOptions.pullDown) {
      await this.getDataInfo();
    }

    uni.stopPullDownRefresh();
  },
  onShareAppMessage() {
    if (!this.mixinViewOptions.share || !this.mixinShareOptions) return false;
    let op = this.mixinShareOptions || {};
    let q = op.query || {};
    let pages = getCurrentPages();
    let page = pages[pages.length - 1];
    let path = page.route;
    let options = page.options;
    if (typeof options === "object" && Object.keys(options).length) {
      path += "?" + qs.stringify(options);
    }
    return {
      title: op.title || "",
      path: op.path || path,
      query: q,
    };
  },
  onShareTimeline() {
    let op = this.mixinShareOptions || {};
    let q = op.query || {};
    return {
      ...op,
      title: op.title,
      query: {
        ...this.dataForm,
        ...q,
      },
    };
  },
};